
#import "RNWalkCounter.h"
#import "HealthKitManager.h"

NSString *const kOnStepRunning = @"onStepRunning";

@interface RNWalkCounter ()

/// 步数
@property (nonatomic, assign) double stepCount;

@end

@implementation RNWalkCounter

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

RCT_EXPORT_MODULE()

#pragma mark - constants to export

- (NSDictionary *)constantsToExport
{
    return @{
        kOnStepRunning: kOnStepRunning,
    };
}

#pragma mark - supported events

- (NSArray<NSString *> *)supportedEvents
{
    return @[
        kOnStepRunning,
    ];
}

#pragma mark - Lifecycle

- (void)startObserving
{
    
}

- (void)stopObserving
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -- export method to js

/**
 * 健康数据授权、启动监听
 */
RCT_EXPORT_METHOD(startCounter) {
    [[HealthKitManager shareInstance] authorizeHealthKit:^(BOOL success, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        if (success) {
            [[HealthKitManager shareInstance] observeStepCountChanged:^(HKObserverQuery * _Nonnull query, HKObserverQueryCompletionHandler  _Nonnull completionHandler, NSError * _Nullable error) {
                [[HealthKitManager shareInstance] getStepCount:^(double value, NSError * _Nonnull error) {
                    NSLog(@"value1:%f", value);
                    if (self.stepCount != value) {
                        self.stepCount = value;
                        [self postMessageNotif:@{@"steps": @((NSInteger)value)} messageType:kOnStepRunning];
                    }
                }];
            }];
        }
    }];
}

#pragma mark - Utils

- (void)postMessageNotif:(id)data messageType:(NSString *)type{
    
#if __has_include(<React/RCTEventEmitter.h>)
    if (self.bridge) {
        [self sendEventWithName:type body:data];
    }
#else
    if (self.bridge) {
        [self.bridge.eventDispatcher sendDeviceEventWithName:type
                                                        body:data];
    }
#endif
    
}

@end
  
